package cn.buk.tms.eotms.service;

import cn.buk.common.JsonResult;
import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.common.util.DateUtil;
import cn.buk.common.util.VerifyCodeUtil;
import cn.buk.jedis.RedisDao;
import cn.buk.tms.eotms.dao.EnterpriseDao;
import cn.buk.tms.eotms.dto.AccessTokenDto;
import cn.buk.tms.eotms.dto.PassengerDto;
import cn.buk.tms.eotms.dto.VaasConfigDto;
import cn.buk.tms.eotms.entity.*;
import cn.buk.tms.eotms.sc.SearchFlightOrderCriteria;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author yfdai
 */
@Service
public class EnterpriseServiceImpl extends BaseAbstractService implements EnterpriseService {

  private final static Logger logger = LogManager.getLogger(EnterpriseServiceImpl.class);

  @Autowired
  private EnterpriseDao enterpriseDao;

  @Autowired
  private RedisDao redisDao;

  @Override
  public List<PassengerDto> searchPassengers(final int userId, SearchFlightOrderCriteria sc) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);
    final int enterpriseId = getEnterpriseIdByUserId(userId);

    Set<String> roles = getRolesByUserId(enterpriseId, userId);
    logger.info("{}, {}, {}, {}", ownerId, customerId, enterpriseId, roles);
    //管理员可以查看所有的员工信息
    //其它可以查看本部门所有的员工信息
    if (!roles.contains("ROLE_ADMIN")) {
      //只能查看本部门的
      int deptId = getCustomerDeptIdByUserId(userId);
      if (deptId > 0) {
        sc.setDepartmentId(deptId);
      } else {
        Integer passengerId = getPassengerIdByUserId(userId);
        sc.setPassengerId(passengerId);
      }
    }

    List<Passenger> passengers = enterpriseDao.searchPassengers(ownerId, customerId, sc);
    List<PassengerDto> dtos = new ArrayList<>();

    for (Passenger passenger : passengers) {
      PassengerDto dto = PassengerDto.createBy(passenger);

      dtos.add(dto);
    }

    return dtos;
  }

  @Override
  public List<CustomerDepartment> searchDepartments(int userId, CommonSearchCriteria sc) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    return enterpriseDao.searchDepartments(ownerId, customerId, sc);
  }

  @Override
  public JsonResult createOrUpdateDepartment(int userId, CustomerDepartment dto) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    if (dto == null || dto.getName() == null || dto.getName().length() < 2) {
      return JsonResult.createJsonResult(-1, "部门名称是必需的");
    }

    Customer customer = new Customer();
    customer.setId(customerId);

    dto.setCustomer(customer);


    JsonResult jsonResult = new JsonResult();
    jsonResult.setStatus("ER");

    int status = enterpriseDao.createOrUpdateDepartment(ownerId, dto);
    if (status > 0) {
      jsonResult.setStatus("OK");
    } else {
      jsonResult.setErrcode(status);
    }

    return jsonResult;
  }

  @Override
  public PassengerDto getPassengerInfo(int userId, int id) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    Passenger passenger = enterpriseDao.getPassengerById(ownerId, customerId, id);
    if (passenger == null) {
      return null;
    }

    return PassengerDto.createBy(passenger);
  }

  /**
   * 获取访问令牌
   * @param grantType
   * @param appId
   * @param appSecret
   * @return
   */
  @Override
  public AccessTokenDto getAccessToken(String grantType, String appId, String appSecret) {
    AccessTokenDto dto = new AccessTokenDto();
    //1.校验grantType是否等于client_credential
    if (!"client_credential".equalsIgnoreCase(grantType)) {
      dto.setErrcode(40002);
      dto.setErrmsg("请确保grant_type字段值为client_credential");
      return dto;
    }
    //2.查找appid，并校验其secret key是否正确
    AppIdInfo appIdInfo = enterpriseDao.searchAppId(appId);
    if (appIdInfo == null || !appIdInfo.getSecret().equalsIgnoreCase(appSecret)) {
      dto.setErrcode(40001);
      dto.setErrmsg("AppSecret错误");
      return dto;
    }
    //3.如果限制ip的话，检验ip是否符合
    //4.生成新的access token，并失效原有的access token
    final String token0 = appId + DateUtil.getCurDateTime().getTime() + appSecret;
    final String accessToken = VerifyCodeUtil.MD5(token0);

    final String key = "appid:" + appId + ":access_token";
    //4.1 失效原有的
    final String oldAccessToken = redisDao.getStr(key);
    if (oldAccessToken != null) {
      redisDao.remove(key);
      redisDao.remove("access_token:" + oldAccessToken);
    }

    redisDao.setAndExpire(key, accessToken.getBytes(), 7200);
    redisDao.setAndExpire("access_token:" + accessToken, key.getBytes(), 7200);
    System.out.println("access_token:" + accessToken);

    dto.setAccessToken(accessToken);
    dto.setExpiresIn(7200);
    dto.setErrcode(0);

    return dto;
  }

  @Override
  public boolean validateAccessToken(String accessToken) {
    final String key = "access_token:" + accessToken;
    return redisDao.getStr(key) != null;
  }

}
